import {upload} from "./upload";

export enum messageType {
    NOTICE = 'notice',
    USER_MESSAGE_TYPE = 'user_message_type'
}

export const toast = (title: string) => {
    uni.showToast({
        title: title,
        icon: 'none'
    })
}

export const copyValueToTarget = (target, source) => {
    const newObj = Object.assign({}, target, source);
    // 删除多余属性
    Object.keys(newObj).forEach((key) => {
        // 如果不是target中的属性则删除
        if (Object.keys(target).indexOf(key) === -1) {
            delete newObj[key];
        }
    });
    // 更新目标对象值
    Object.assign(target, newObj);
};

export const modal = (title: string, content: string, confirmText: string = "确定") => {
    return new Promise((resolve) => {
        uni.showModal({
            title: title,
            content: content,
            confirmText: confirmText,
            cancelText: "取消",
            success: (res: any) => {
                if (res.confirm) {
                    resolve(true)
                } else {
                    resolve(false)
                }
            }
        })
    })
}

export const toPath = (path: string) => {
    const pages = getCurrentPages()
    const idx = pages.findIndex(p => p.route === path.replace(/^\//, ''))
    if (idx !== -1) {
        console.log('存在堆栈')
        uni.navigateBack({delta: pages.length - idx - 1})
    } else {
        uni.navigateTo({url: path})
    }
}

export const back = () => {
    uni.navigateBack()
}

export const redirectTo = (path: string) => {
    uni.redirectTo({
        url: path
    })
}

export const switchTab = (path: string) => {
    uni.switchTab({
        url: path
    })
}

// 计算vip剩余时间
export function leftDH(targetTs) {
    const now = Date.now();
    if (targetTs <= now) return '0天0时';

    const diff = targetTs - now;

    const day = Math.floor(diff / 86400000);          // 1 天 = 86400000 ms
    const hour = Math.floor((diff % 86400000) / 3600000);

    return `${day}天${hour}时`;
}

// TODO 会话计数处理
interface Conversation {
    conversationId: number,
    count: number
}

// 更新会话的新数据
export const updateConversation = (
    id: number,
    count: number,
    type: number      // 如果暂时不用，就先注明“预留”
) => {
    let conversationList: Array<Conversation> =
        uni.getStorageSync('conversations') || [];
    const target = conversationList.find(item => item.conversationId === id);
    if (target) {
        target.count += count;
    } else {
        conversationList.push({conversationId: id, count});
    }
    uni.setStorageSync('conversations', conversationList);
};

/**
 * 根据会话 id 获取本地缓存中的计数
 * @param id 会话 id
 * @returns 该会话的当前计数（找不到返回 0）
 */
export const getConversationCount = (id: number): number => {
    const list: Array<Conversation> =
        uni.getStorageSync('conversations') || [];
    const target = list.find(item => item.conversationId === id);
    return target ? target.count : 0;
};

/**
 * 根据会话 id 把对应计数重置为 0
 * @param id 会话 id
 */
export const resetConversationCount = (id: number): void => {
    const list: Array<Conversation> =
        uni.getStorageSync('conversations') || [];
    const target = list.find(item => item.conversationId === id);
    if (target) {
        target.count = 0;
        uni.setStorageSync('conversations', list);
    }
};

// TODO 图片选择上传
export function imgUpload(count: number): Promise<any> {
    return new Promise((resolve, reject) => {
        uni.chooseImage({
            count,
            sizeType: ['original'],
            sourceType: ['album'],
            success: async (res) => {
                try {
                    const file = res.tempFiles[0]
                    if (file.size > 1024 * 1024 * 16) {
                        toast("图片大小不能超过10M")
                        return
                    }
                    const filePath = res.tempFilePaths[0]
                    const data = await upload(filePath);
                    // 业务成功
                    if (data.code === 0) return resolve(data.data);
                    reject(data); // 把错误抛给调用方
                } catch (err) {
                    // 网络/解析/上传异常
                    reject(err);
                }
            },
            fail: reject, // 用户取消或微信拒绝
        });
    });
}

export function fmtDistance(d) {
    d = Number(d) || 0
    if (d >= 1000) {
        const km = (d / 1000).toFixed(1)
        return km.replace('.0', '') + 'km'
    }
    return Math.round(d) + 'm'
}

// 地图导航
export function navigationFn(val) {
    uni.openLocation({
        latitude: Number(val.latitude), //维度
        longitude: Number(val.longitude), //经度
        scale: 12, //缩放比例，范围5~18，默认为18 .match(reg)[0]
        name: '' + val.name,
        address: '' + val.companyDetailAddress,
    });
}